package com.iris.live.services.common;

import com.mysql.jdbc.Connection;
import com.mysql.jdbc.PreparedStatement;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Properties;

/**
 * Created by Huangyongping on 2016/10/17.
 */
public class JDBCUtils {
    private static Logger logger = LoggerFactory.getLogger(JDBCUtils.class);

    static Properties pros = null;

    static {   //程序启动时加载,只会被加载一次
        pros = new Properties();
        try {
            //获取配置文件
            pros.load(Thread.currentThread().getContextClassLoader().getResourceAsStream("application.dev.properties"));
        } catch (IOException e) {
            logger.error("获取配置信息异常。", e);
        }
    }

    public static Connection getMysqlConn() {
        String driver = pros.getProperty("db.driverClassName");
        String url = pros.getProperty("db.url");
        String username = pros.getProperty("db.username");
        String password = pros.getProperty("db.password");
        Connection conn = null;
        try {
            Class.forName(driver);
            conn = (Connection) DriverManager.getConnection(url, username, password);
        } catch (Exception  e) {
            logger.error("获取数据库连接异常。", e);
        }

        return conn;
    }

    public static void close(ResultSet rs, PreparedStatement ps, Connection conn) {
        try {
            if (rs != null) {
                rs.close();
            }
            if (ps != null) {
                ps.close();
            }
            if (conn != null) {
                conn.close();
            }
        } catch (SQLException e) {
            logger.error("关闭数据库连接异常。", e);
        }
    }
}
